/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dk.itu.samd.group2.tagapastry.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.net.UnknownHostException;
import java.net.SocketException;

/**
 *
 * @author frgr
 */
public class Networking {

  public static InetAddress discoverAddress(boolean verbose, boolean useLocal) throws UnknownHostException, SocketException {
	  
    InetAddress addr = InetAddress.getLocalHost();
    if(useLocal)
    	return addr;
    
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
      NetworkInterface n = (NetworkInterface) interfaces.nextElement();
      if (!n.isLoopback()) {
	Enumeration<InetAddress> addresses = n.getInetAddresses();
	while (addresses.hasMoreElements()) {
	  InetAddress addr1 = (InetAddress) addresses.nextElement();

	  if (!addr1.isLinkLocalAddress()) {
	    addr = addr1;
	  }

	  if (verbose) {
	    System.out.println("----------------------------");
	    System.out.println("" + addr);
	    System.out.println("hostname: " + addr.getCanonicalHostName());
	    System.out.println("isAnyLocal: " + addr.isAnyLocalAddress());
	    System.out.println("isLinkLocal: " + addr.isLinkLocalAddress());
	  }
	}
      }

    }

    return addr;
  }

}
